<template>
  <div :class="$style.transfer">
    <ContentWrap>
      <el-tabs v-model="activeTab">
        <el-tab-pane name="queue" label="转坐席">
          <FormContainer :column="4">
            <el-form ref="queue" :model="queueData" :rules="queueRules" label-width="80px">
              <el-form-item prop="workno" label="坐席标识">
                <el-select
                  v-model.trim="queueData.workno"
                  clearable
                  filterable
                  placeholder="请输入坐席标识"
                  :remote-method="getStaffInfo"
                  remote
                >
                  <el-option v-for="(a,i) in agentList" :key="i" :value="a.platformNo" :label="`${a.staffName}(${a.accountNo})`"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="skillid" label="技能组">
                <!-- <el-select v-model="queueData.skillid" placeholder="请选择技能组" clearable filterable>
                  <el-option v-for="(sg,i) in skillList" :key="i" :value="sg.id" :label="sg.name" />
                </el-select> -->
                <el-select v-model="queueData.skillid" placeholder="请选择技能组" multiple collapse-tags clearable filterable @change="changeHandle">
                  <el-option v-for="(sg,i) in skillGroupList" :key="i" :value="sg.skillNo" :label="sg.skillName" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <Button type="primary" enter @click="queueQueryHandle">查询</Button>
              </el-form-item>
            </el-form>
          </FormContainer>
          <div>
            <Table v-loading="loading" :data="queueAgentList" :filter-fun="queueFilterFun">
              <el-table-column label="坐席编号" prop="workno"></el-table-column>
              <el-table-column label="坐席姓名" prop="staffName">
                <template v-slot="{row}">
                  <span>{{ `${row.staffName}(${row.accountNo})`||row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="技能组" prop="organization"></el-table-column>
              <el-table-column label="操作" align="right">
                <template v-slot="{row}">
                  <a href="javascript:void(0)" :class="$style.a" @click="transferQueueHandle(row, 0)">释放转</a>
                  <!-- <a href="javascript:void(0)" :class="$style.a" @click="transferQueueHandle(row, 4)">合并转</a> -->
                  <a href="javascript:void(0)" :class="$style.a" @click="consultHandle(row)">咨询转</a>
                </template>
              </el-table-column>
            </Table>
          </div>
        </el-tab-pane>
        <el-tab-pane name="skill" label="转技能组">
          <table-box ref="table" :table-config="tableConfig"></table-box>
        </el-tab-pane>
      </el-tabs>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
// import SeatChartList from './components/SeatChartList'
import { getStaffInfo } from '@/api/staffInfo'
import { filtersRaw, pageRequsetBody } from '@/utils'
import { mapGetters } from 'vuex'
import { getBusinessAll } from '@/api/business'
import Table from './components/Table'
import { getSkillGroup, pageSkillMembers } from '@/api/skillGroup'
import { putCreate } from '@/api/telRecord'
export default {
  name: 'Transfer',
  components: {
    ContentWrap,
    FormContainer,
    Table
  },
  data() {
    const validatorSkillId = (r, v, c) => {
      if (v instanceof Array && v.length > 0) {
        c()
      } else {
        c(new Error('请选中技能组'))
      }
    }
    return {
      loading: false,
      // 激活的标签页
      activeTab: 'queue',
      // 分支机构列表
      orgList: [],
      // 转队列查询
      queueData: {
        workno: '',
        skillid: []
      },
      agentList: [], // 员工信息
      queueRules: {
        // workno: [{ required: true, message: '请选择分支机构', trigger: 'change' }],
        skillid: [{ required: true, type: 'array', message: '请选择技能组', trigger: 'change' },
          { required: true, validator: validatorSkillId, trigger: 'chenge' }]
      },
      // 根据技能查询出来的坐席队列
      queueAgentList: [],
      tableConfig: {
        interfacePath: '/call-center/api/v1/skillInfo/page',
        pageFlag: true,
        hideFuncBar: true,
        // 表格字段动态配置
        setting: [
          {
            label: '序号',
            type: 'index',
            width: '80',
            align: 'center',
            formatData: v => v.keyIndex + 1
          },
          {
            prop: 'skillName',
            label: '技能'
          },
          {
            label: '操作',
            align: 'center',
            overflowHidden: false,
            render: (_, row) => {
              // <Button isText type='text' onClick={() => this.transferSkillHancle(row, 4)}>合并转</Button>
              return (
                <div class={this.btn}>
                  <Button isText type='text' onClick={() => this.transferSkillHancle(row, 0)}>释放转</Button>
                  <Button isText type='text' onClick={() => this.consultSkillHandle(row)}>咨询转</Button>
                </div>
              )
            }
          }

        ]
      },
      // 所有技能组
      skillGroupList: [],
      // 当前技能业务平台id
      skillGid: []
    }
  },
  computed: {
    ...mapGetters(['agentState', 'skillList', 'statusList', 'callInfo', 'recordList', 'isCallOut'])
  },
  created() {
    if (!this.agentState.talk && !this.$dev) {
      this.$router.push({ name: 'Index' })
      return
    }
    this.getBusinessGroupAll()
    this.getSkillGroup()
    this.getStaffInfo('') // 获取20个职员信息
  },
  methods: {
    // 技能变化
    changeHandle(v) {
      const skillGid = []
      for (const id of v || []) {
        for (const d of this.skillGroupList) {
          if (id === d.skillNo) {
            skillGid.push(d.id)
          }
        }
      }
      this.skillGid = skillGid
    },
    // 获取员工列表信息
    getStaffInfo(v) {
      const data = {
        filtersRaw: [],
        pageFlag: true
      }
      // 验证是名字还是拼音
      if (/^[a-zA-Z]+$/.test(v)) {
        data.filtersRaw.push(filtersRaw('accountNo', v, 'like'))
      } else {
        data.filtersRaw.push(filtersRaw('staffName', v, 'like'))
      }
      getStaffInfo(pageRequsetBody(data)).then(res => {
        this.agentList = res.data.records
      })
    },
    // 多promise处理
    async handlePromise(promiseList) {
      const resList = []
      for (const p of promiseList) {
        await p.then(res => {
          resList.push(res)
        }).catch(() => {})
      }
      return resList
    },
    // 对列相关
    // 发起查询
    queueQueryHandle() {
      this.$refs.queue.validate().then(async() => {
        this.queueAgentList = []
        this.loading = true
        const skillList = this.queueData.skillid.map(e => this.$cps.queryAgentBySkill(e))
        const resList = []
        await this.handlePromise(skillList).then(res => {
          res.forEach(e => {
            const vdnData = e.data.agentDetail.filter(e => { // 只显示空闲坐席
              return e.status === 4
            })
            resList.push(...vdnData)
          })
        }).catch(() => {
          this.loading = false
        })
        const skillMembers = []
        await this.pageSkillMembers().then(res => {
          res.forEach(r => skillMembers.push(...r.data.records))
        }).catch(() => {
          this.loading = false
        })
        const queueAgentList = this.concatData(resList, skillMembers)
        // 去重
        const q = Object.create(null)
        const rmIndex = []
        for (let i = 0; i < queueAgentList.length; i++) {
          const v = queueAgentList[i]
          if (v.workno in q) {
            const qv = queueAgentList[q[v.workno]]
            qv.skillName ? qv.skillName += v.skillName : qv.skillName = v.skillName
            rmIndex.push(i)
          } else {
            q[v.workno] = i
          }
        }
        for (const i of rmIndex) {
          queueAgentList.splice(i, 1)
        }
        this.queueAgentList = queueAgentList
        this.loading = false
      })
    },
    // 合并vdn与员工数据
    concatData(vdnData, staffData) {
      for (const v of vdnData) {
        for (const s of staffData) {
          if (v.workno === s.platformNo) {
            for (const key of Object.keys(s)) {
              v[key] = s[key]
            }
            continue
          }
        }
      }
      return vdnData
    },
    // 查询数据时对数据做筛选
    queueFilterFun(data) {
      let t = []
      if (this.queueData.workno !== '') {
        t = data.filter(e => e.workno === this.queueData.workno)
      } else {
        t = data
      }
      return t || []
    },
    // 转队列坐席
    transferQueueHandle(row, mode) {
      this.$msgbox({
        title: '转坐席',
        message: '确认转移？',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        const callData = this.genCallData('release')
        this.$cps.transfer('2', row.workno, mode, callData).then(() => {
          this.$callOperatorLogSuccess(5) // 转移成功
          this.$notifySuccess('转移成功！')
          this.putTelRecord()
        }).catch(() => {
          this.$callOperatorLogFail(5) // 转移失败
        })
      })
    },

    // 获取组织
    getBusinessGroupAll() {
      getBusinessAll().then(res => {
        this.orgList = res.data
      })
    },
    // 获取指定技能下的员工信息
    pageSkillMembers() {
      const data = {
        pageFlag: false
      }
      return this.handlePromise(this.skillGid.map(id => {
        return pageSkillMembers(id, pageRequsetBody(data))
      }))
    },
    // 转移到技能组
    transferSkillHancle(row, mode) {
      this.$msgbox({
        title: '转技能组',
        message: '确认转移？',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        const callData = this.genCallData('release')
        this.$cps.transfer('1', row.skillNo, mode, callData).then(() => {
          this.$callOperatorLogSuccess(5) // 转移成功
          this.$notifySuccess('转移成功！')
          this.putTelRecord()
        }).catch(() => {
          this.$callOperatorLogFail(5) // 转移失败
        })
      })
    },
    // 获取所有技能组
    getSkillGroup() {
      return getSkillGroup().then(res => {
        this.skillGroupList = res.data
      })
    },
    // 咨询坐席/技能组
    consultHandle(row) {
      this.$msgbox({
        title: '内部咨询',
        message: '确认咨询？',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        const callData = this.genCallData()
        this.$cps.consult(row.workno, 2, 1, callData).then(() => {
          this.$callOperatorLogSuccess(5) // 转移成功
          // this.$notifySuccess('咨询转成功！')
          this.putTelRecord()
        }).catch(() => {
          this.$callOperatorLogFail(5) // 转移失败
        })
      })
    },
    // 咨询技能组
    consultSkillHandle(row) {
      this.$msgbox({
        title: '内部咨询',
        message: '确认咨询？',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        const callData = this.genCallData()
        this.$cps.consult(row.skillNo, 1, 1, callData).then(() => {
          // this.$notifySuccess('咨询转成功！')
          this.putTelRecord()
        })
      })
    },
    // 转移成功,修改通话记录
    putTelRecord() {
      const callid = this.callInfo.callid
      let id
      if (this.isCallOut) {
        id = this.callInfo.callOutRecordId
      } else {
        const rl = this.recordList[callid]
        const cd = rl.callData
        id = rl.recordId
        // 来电转移时设置标志
        cd.type = 'transfer'
        cd.display = false
      }
      putCreate({
        id,
        // callType: 5 // 没有这个类型了
        transfer: 1 // 转接类型 0未转接，1转出方，2转入方
      }).catch(() => {
        console.log('转移时保存通话记录失败！')
      })
    },
    // 序列化随路数据 //区分释放转还是咨询转
    genCallData(type = 'consult') {
      const callid = this.callInfo.callid
      const data = {
        callTel: this.callInfo.callTel,
        type
      }
      if (this.isCallOut) {
        data.recordId = this.callInfo.callOutRecordId
        data.goOut = true
      } else {
        data.recordId = this.recordList[callid].recordId
        // data.type = 'transfer'
        data.display = true
        data.zrcdbh = this.recordList[callid].callData.zrcdbh
      }
      return JSON.stringify(data)
    }

  }
}
</script>
<style lang="scss" module>
@import "@/styles/mixin.scss";
.transfer {
  .queryContainer{
    margin: 10px 0;
    @include flex($align: center);
    &>span{
      padding-right: 10px;
      flex: 0 0 auto;
    }
    &>.input{
      flex: 0 0 200px;
    }
  }
  .btn{
    margin: 0;
    padding: 10px 0;
  }
  .a{
    color: #16BC83;
  }
  .a+.a{
    padding-left: 10px;
  }
}
</style>
